/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.majc.travelapplication.DB;

import edu.chl.majc.travelapplication.core.Flight;
import edu.chl.majc.travelapplication.core.Flight_;
import java.io.Serializable;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;

/**
 *
 * @author lujoel
 */
@Stateless
public class JPAFlightController implements Serializable{ 
    
    @PersistenceContext(unitName= "travel_pu" )
    private EntityManager em;

    public JPAFlightController() {
    }

    public void create(Flight entity) {
        em.persist(entity);
    }

    public void edit(Flight entity) {
        em.merge(entity);
    }

    public void remove(Flight entity) {
        em.remove(em.merge(entity));
    }

    public Flight find(String id) {
        return em.find(Flight.class, id);
    }

    public List<Flight> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Flight.class));
        return em.createQuery(cq).getResultList();
    }

    public List<Flight> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Flight.class));
        javax.persistence.Query q = em.createQuery(cq);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        javax.persistence.criteria.CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<Flight> rt = cq.from(Flight.class);
        cq.select(em.getCriteriaBuilder().count(rt));
        javax.persistence.Query q = em.createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }
    
    public List<String> getDestinations(){
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        Root<Flight> flight = cq.from(Flight.class);
        Path<String> destination = flight.get(Flight_.toAirport);
        cq.select(destination).distinct(true);
        return em.createQuery(cq).getResultList();
    }    
}

